This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 9.4.1
Category: Required
Analysis Type: Decidable,Single Translation Unit
Amplification
A final else
shall always be provided whenever an if
statement is followed by a sequence of one or more else
if
constructs.
Note: a final else
statement is not required for a simple if
statement.
Rationale
Terminating a sequence of if ... else if
constructs with an else
statement is defensive programming, complementing the
requirement for a default
clause in a switch
statement (see MISRA C++ 2023 Rule 9.4.2 (The structure of a
switch
statement shall be appropriate)).
The addition of an else
statement, even when empty, indicates that consideration has been given regarding the behaviour when all other
conditions evaluate to false
.
Example
void f1( bool flag_1, bool flag_2 )
{
if ( flag_1 )
{
action_1();
}
else if ( flag_2 )
{
action_2();
} // Non-compliant
}
void f2(bool flag_1, bool flag_2)
{
if ( flag_1 )
{
action_1();
}
else if ( flag_2 )
{
action_2();
}
else // Compliant
{
}
}
void f3( bool flag )
{
if ( flag )
{
action_1();
} // Simple 'if' - rule does not apply
}
Copyright The MISRA Consortium Limited © 2023